package com.kim.rssreader.utils;

import java.io.IOException;
import java.io.InputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.kim.rssreader.db.DBDAO;
import com.kim.rssreader.db.DataFactory;
import com.kim.rssreader.domain.constant.RssColumnConstant;
import com.kim.rssreader.service.RssColumnUpdateService.RssColumnConfCallback;
import com.kim.rssreader.service.RssColumnUpdateService.RssColumnDataCallback;
import com.kim.rssreader.utils.NetUtil.NetProcessComplete;

import android.content.Context;

public class RssColumnUpdateUtils {

	/*
	 * { "vc": 0, "d": [ { "c": 1, "rD": { "rN": "newName", "rU":
	 * "http://www.example.com", "fs": "start", "fe": "end" } }, { "c": 1, "rD":
	 * { "rN": "newName", "rU": "http://www.example.com", "fs": "start", "fe":
	 * "end" } } ] }
	 */

	/**
	 * rss栏目版本配置文件
	 */
	public static final String RSSCOLUMN_CONFIG = "rsscolumn_config";

	/**
	 * rss栏目更新版本
	 */
	public static final String RSSCOLUMN_RV = "rv";

	/**
	 * rss栏目数据更新地址
	 */
	public static final String RSSCOLUMN_RU = "ru";

	public static final String FLAG_VERSION_CODE = "vc"; // 版本号
	public static final String FLAG_RSSCOLUMN_DATA = "d"; // rss栏目数据集
	public static final String FLAG_RSSCOLUMN_CATEGORY = "c"; // rss栏目类别
	public static final String FLAG_RSSCOLUMN_DATA_ITEM = "rD"; // rss栏目数据项
	public static final String FLAG_RSSCOLUMN_NAME = "rN"; // rss栏目名称
	public static final String FLAG_RSSCOLUMN_URL = "rU"; // rss栏目url地址
	public static final String FLAG_RSSCOLUMN_FS = "fs"; // rss栏目内容截取起始标记
	public static final String FLAG_RSSCOLUMN_FE = "fe"; // rss栏目内容截取结束标记

	/**
	 * 更新rss栏目版本并下载rss栏目数据
	 * 
	 * @param context
	 */
	public static final void updateRssColumn(final Context context,
			final RssColumnConfCallback rssColumnConfCallback) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				NetUtil.getInputStream(
						ValueConstant.RSS_COLUMN_UPDATE_CONFIG_FILE_URL,
						new NetProcessComplete() {

							@Override
							public void onProcess(InputStream inputStream) {
								try {
									String jsonStr = NetUtil
											.convertInputStream2String(inputStream);
									JSONObject jsonObject = new JSONObject(
											jsonStr);
									int versionCodeNew = jsonObject
											.getInt(RSSCOLUMN_RV);
									int versionCodeLocal = getLocalVersionCode(context);
									if (versionCodeLocal >= versionCodeNew) {
										rssColumnConfCallback.onComplete();
										return;
									}
									String url = jsonObject
											.getString(RSSCOLUMN_RU);

									System.out.println("url:" + url);

									updateLocalVersionCode(context,
											versionCodeNew);
									updateRU(context, versionCodeNew, url);
									rssColumnConfCallback.onComplete();
								} catch (Exception e) {
									rssColumnConfCallback.onError();
									e.printStackTrace();
								}
							}
						});
			}
		}).start();
	}

	/**
	 * 抓取rss栏目数据并插入到数据库
	 * 
	 * @param context
	 * @param dbdao
	 */
	public static final void fetchRssColumnData(final Context context,
			final RssColumnDataCallback rssColumnDataCallback) {
		NetUtil.getInputStream(getRU(context, getLocalVersionCode(context)),
				new NetProcessComplete() {

					@Override
					public void onProcess(InputStream inputStream) {

						if (inputStream == null) {
							rssColumnDataCallback.onError();
							return;
						}

						String jsonStr;
						try {
							jsonStr = NetUtil
									.convertInputStream2String(inputStream);
							System.out.println(jsonStr);
							JSONObject jsonObject = new JSONObject(jsonStr);
							JSONArray rssDataArray = jsonObject
									.getJSONArray(FLAG_RSSCOLUMN_DATA);
							if (rssDataArray != null
									&& rssDataArray.length() > 0) {
								JSONObject jsonItem = null;
								String[] sqls = new String[rssDataArray
										.length()];
								for (int i = 0; i < rssDataArray.length(); i++) {
									jsonItem = rssDataArray.getJSONObject(i);
									if (jsonItem == null) {
										continue;
									}
									String category = jsonItem
											.getString(FLAG_RSSCOLUMN_CATEGORY);
									JSONObject rssData = jsonItem
											.getJSONObject(FLAG_RSSCOLUMN_DATA_ITEM);
									String rssColumnName = rssData
											.getString(FLAG_RSSCOLUMN_NAME);
									String rssColumnUrl = rssData
											.getString(FLAG_RSSCOLUMN_URL);
									String rssColumnFS = rssData
											.getString(FLAG_RSSCOLUMN_FS);
									String rssColumnFE = rssData
											.getString(FLAG_RSSCOLUMN_FE);
									String sql = String
											.format(DataFactory.sql_insert_rsscolumn_template,
													DigestUtils
															.shaHex(rssColumnName),
													rssColumnName,
													rssColumnUrl, "0", "0", "",
													rssColumnFS, rssColumnFE,
													DigestUtils
															.shaHex(category));
									sqls[i] = sql;
								}
								DBDAO.getInstance(context)
										.insertRssColumn(sqls);
							}
							rssColumnDataCallback.onComplete();
						} catch (Exception e) {
							rssColumnDataCallback.onError();
							e.printStackTrace();
						}
					}
				});
	}

	/**
	 * 获取本地rss栏目更新版本号
	 * 
	 * @param context
	 * @return String
	 */
	public static int getLocalVersionCode(Context context) {
		return SharedPreferencesUtils.getValueInt(RSSCOLUMN_RV,
				RSSCOLUMN_CONFIG, context);
	}

	/**
	 * 设置本地rss栏目版本号
	 * 
	 * @param context
	 * @param newVersionCode
	 */
	public static void updateLocalVersionCode(Context context,
			int newVersionCode) {
		SharedPreferencesUtils.setValue(RSSCOLUMN_RV, newVersionCode,
				RSSCOLUMN_CONFIG, context);
	}

	/**
	 * 获取rss栏目更新版本对应的url地址
	 * 
	 * @param context
	 * @param versionCode
	 * @return
	 */
	public static String getRU(Context context, int versionCode) {
		return SharedPreferencesUtils.getValueString(
				RSSCOLUMN_RU + versionCode, RSSCOLUMN_CONFIG, context);
	}

	/**
	 * 设置rss栏目更新版本对应的url地址
	 * 
	 * @param context
	 */
	public static void updateRU(Context context, int targetVersionCode,
			String url) {
		SharedPreferencesUtils.setValue(RSSCOLUMN_RU + targetVersionCode, url,
				RSSCOLUMN_CONFIG, context);
	}
}
